import axios from 'axios'

export default {
  namespaced: true,
  state: { list: [] },
  mutations: {
    // 更新list数据方法
    updatelist (state, newList) {
      state.list = newList
    },
    // 更新count方法
    updateCount (state, obj) {
      let row = state.list.find(item => item.id === obj.id)
      row.count = obj.count
    }
  },
  getters: {
    count (state) {
      return state.list.reduce((t, c) => (t += c.count), 0)
    },
    amount (state) {
      return state.list.reduce((t, c) => (t += c.count * c.price), 0)
    }
  },
  actions: {
    // 发送ajax请求
    async getListAsync (store) {
      const { data: res } = await axios.get('http://localhost:3000/list')
      console.log('哈哈哈哈')
      console.log(res)
      store.commit('updatelist', res)
    },
    async updateCountAsync (store, obj) {
      // 发送请求更改服务器上的数据
      await axios.patch(`http://localhost:3000/list/${obj.id}`, obj)
      // 更改vuex上的数据
      store.commit('updateCount', obj)
    }
  }
}
